package com.xlh.security;

import com.xlh.common.ResultEnum;
import com.xlh.entity.UserEntity;
import com.xlh.enums.RoleEnum;
import com.xlh.exception.NotFoundException;
import com.xlh.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * @author cheer
 */
@Component
public class SpringSecurityUserInfoHolder implements UserInfoHolder {

    @Autowired
    private UserService userService;

    @Override
    public UserEntity getUser() {
        if (SecurityContextHolder.getContext().getAuthentication().getPrincipal().equals("anonymousUser")) {
            return null;
        }
        return ((CustomUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUserEntity();
    }

    @Override
    public Long getUserId() {
        if (!isLogin()) {
            throw new NotFoundException(ResultEnum.UNAUTHORIZED.getMessage());
        }
        return getUser().getId();
    }

    @Override
    public Boolean isAdmin() {
        if (!isLogin()) {
            throw new NotFoundException(ResultEnum.UNAUTHORIZED.getMessage());
        }
        int roleId = getUser().getRole();
        return roleId == RoleEnum.ADMIN.getRoleCode() || roleId == RoleEnum.SUPER_ADMIN.getRoleCode() ||
                roleId == RoleEnum.INTERNET_ADMIN.getRoleCode();
    }

    @Override
    public Boolean isStudent() {
        if (!isLogin()) {
            throw new NotFoundException(ResultEnum.UNAUTHORIZED.getMessage());
        }
        return Objects.equals(getUser().getRole(), RoleEnum.STUDENT.getRoleCode());
    }

    @Override
    public Boolean isLogin() {
        return getUser() != null;
    }

}
